
package com.sausageking.server.dao;

import java.util.Date;

import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.common.base.Strings;
import com.googlecode.objectify.NotFoundException;
import com.sausageking.server.common.BCrypt;
import com.sausageking.shared.Counter;
import com.sausageking.shared.Merchant;

public class MerchantDaoImpl implements MerchantDao {

  @Override
  public Merchant insert(Merchant merchant) {
    // TODO: increment count and insert merchant in a transaction
    GenericDao<Counter> counterDao = new GenericDao<Counter>(Counter.class);
    Counter counter;
    try {
      counter = counterDao.get(Counter.MERCHANT_ID);
      counter.setCount(counter.getCount() + 1);
    } catch (NotFoundException e) {
      counter = new Counter().setCounterType(Counter.MERCHANT_ID).setCount(1L);
    }
    counterDao.put(counter);
    merchant.setId(counter.getCount());
    merchant.setCreationTime(new Date());
    merchant.setSalt(BCrypt.gensalt());
    GenericDao<Merchant> dao = new GenericDao<Merchant>(Merchant.class);
    dao.put(merchant);
    return merchant;
  }

  @Override
  public Merchant update(Merchant merchant) {
    GenericDao<Merchant> dao = new GenericDao<Merchant>(Merchant.class);
    Merchant merchantToUpdate;
    try {
      merchantToUpdate = dao.get(merchant.getId());
    } catch (EntityNotFoundException e) {
      throw new IllegalArgumentException("Merchant with id:" + merchant.getId()
          + " can not be found.");
    }
    String salt = Strings.isNullOrEmpty(merchantToUpdate.getSalt()) ? BCrypt
        .gensalt() : merchantToUpdate.getSalt();
    merchant.setSalt(salt);
    dao.put(merchant);
    return merchant;
  }

  @Override
  public Merchant getById(Long id) throws EntityNotFoundException {
    GenericDao<Merchant> dao = new GenericDao<Merchant>(Merchant.class);
    Merchant merchant = dao.get(id);
    if (merchant == null) {
      throw new IllegalArgumentException("Merchant with id:" + id
          + " can not be found.");
    }
    merchant.setSalt(null);
    return merchant;
  }

}
